<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        requestName="searchHandle"
        isNeedSelection
        isNeedIndex
        v-model="searchParams"
        :btnList="btnList"
        :total="totalNum"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        :tableData="tableData"
        @remove="operateHandle($event, 'remove')"
        @export="operateHandle($event, 'export')"
        @view="operateHandle($event, 'view')"
        @reject="operateHandle($event, 'reject')"
        @audit="operateHandle($event, 'audit')"
      />
    </div>
    <TrDetail
      v-model="isShowDetailPopup"
      popupTitle="查看详情"
      :leftList="detailList"
      statusModel="hidden"
      :width="1227"
      :detailData="detailData"
      :rightList="recordList"
      :isNeedFooter="false"
      @close="closeDetailPopup"
    >
      <template #bomTable>
        <TrTable
          isPopup
          isNeedIndex
          v-model="bomSearchParams"
          :isNeedPagination="false"
          :tableData="bomTableData"
          :tableColumn="bomTableColumn"
          requestName="getBomListHandle"
          @viewDeatil="getDetailTableHandle($event)"
        />
        <TrDetail
          v-model="isShowDetailInnerPopup"
          popupTitle="查看详情"
          :leftList="detailInnerList"
          statusModel="hidden"
          :width="960"
          :detailData="detailInnerData"
          @close="closeDetailInnerPopup"
          @audit="auditHandle"
        >
        </TrDetail>
      </template>
    </TrDetail>
    <TrEditPopup
      ref="TrEditInnerPopup"
      :width="480"
      v-model="isShowReject"
      title="驳回"
      :valueObj.sync="formRejectObj"
      :list="popupRejectList"
      @close="closeRejectPopup"
      @confrim="rejectConfirmHandle"
    ></TrEditPopup>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  getDetailInner,
  getDetailRight,
  remove,
  getAudit,
  getFileList,
} from "@/api/accoutrement/spotQuery";
import { getColor } from "@/utils/billColor";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-form/Tr-form-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";

export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
  },
  name: "spotQuery",
  data: () => ({
    remarkValue: "",
    uploadList: [],
    tableColumn: [
      {
        type: "text",
        label: "设备点检单号",
        value: "code",
      },
      {
        type: "text",
        label: "资产品牌",
        value: "assetBrandName",
      },
      {
        type: "text",
        label: "资产类型",
        value: "assetTypeName",
      },
      {
        type: "text",
        label: "资产型号",
        value: "assetModelName",
      },
      {
        type: "text",
        label: "设备",
        value: "machineCode",
      },
      {
        type: "text",
        label: "点检人员",
        value: "checkUserName",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "点检结果",
        value: "checkResName",
      },
      // {
      //   type: "text",
      //   label: "创建人员",
      //   value: "createUserName",
      // },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "view",
          },
        ],
        hideBtnList: [
          {
            label: "驳回",
            option: "reject",
          },
          {
            label: "审核",
            option: "audit",
          },
        ],
      },
    ],
    recordList: [
      {
        label: "审核记录",
        type: "record",
        id: "record",
        list: [],
      },
    ],
    searchHideList: [
      {
        id: "billCode",
        label: "设备点检单号",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "assetBrandId",
        label: "资产品牌",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        reviewLabel: "assetBrandName",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-equipment-service/assets-brand/page",
          method: "post",
          searchKey: "brandName",
          rlLabel: "brandName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "assetModelId",
        label: "资产型号",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        reviewLabel: "assetModelName",
        defaultParams: {},
        isNeed: false,
        requestObj: {
          url: "/api/mes-equipment-service/assets-mode/page",
          method: "post",
          searchKey: "assetsModeName",
          rlLabel: "assetsModeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "deviceId",
        label: "设备",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        isNeed: false,
        reviewLabel: "machineCode",
        requestObj: {
          url: "/api/mes-equipment-service/device-ledger/page",
          method: "post",
          searchKey: "machineCode",
          rlLabel: "machineCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "checkUser",
        type: "loadselect",
        width: 33.33,
        label: "点检人员",
        value: "",
        reviewLabel: "checkUserName",
        valueLabel: "checkUserName",
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "account",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "updateUser",
        type: "loadselect",
        width: 33.33,
        label: "修改人员",
        value: "",
        reviewLabel: "updateUser",
        valueLabel: "updateUser",
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "account",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "state",
        label: "状态",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "checkRes",
        label: "点检结果",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 1,
      },
    ],
    btnList: [
      {
        label: "取消",
        option: "remove",
        color: "blue",
        isRelaTable: true,
      },

      {
        label: "驳回",
        option: "reject",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "审核",
        option: "audit",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,
    // 新增通过弹窗
    currentHandle: "",
    usableNum: "",
    materialInfo: {},
    formInnerObj: {},
    formInnerData: {},
    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            width: 33.3,
            text: "设备点检单号",
            id: "code",
          },
          {
            width: 33.3,
            text: "设备品牌",
            id: "assetBrandName",
          },
          {
            width: 33.3,
            text: "资产类型",
            id: "assetTypeName",
          },
          {
            width: 33.3,
            text: "资产型号",
            id: "assetModelName",
          },
          {
            width: 33.3,
            text: "设备",
            id: "machineCode",
          },
          {
            width: 33.3,
            text: "点检结果",
            id: "checkResName",
          },
          {
            width: 33.3,
            text: "状态",
            id: "stateName",
          },
          {
            width: 33.3,
            text: "点检人员",
            id: "checkUserName",
          },
          {
            width: 33.3,
            text: "审核人",
            id: "checkAuditUserName",
          },
          {
            width: 33.3,
            text: "创建时间",
            id: "createTime",
          },
          {
            width: 33.3,
            text: "修改时间",
            id: "updateTime",
          },
        ],
      },
      {
        type: "slot",
        slotName: "bomTable",
        label: "点检项明细",
        slotBottom: 32,
      },
    ],
    isNeedFooter: false,

    currentDetail: "",
    bomSearchParams: {
      current: 1,
      size: 10,
    },
    bomTotal: 0,
    bomTableColumn: [
      {
        type: "text",
        label: "点检项目编码",
        value: "code",
      },
      {
        type: "text",
        label: "点检项目名称",
        value: "name",
      },
      {
        type: "text",
        label: "点检类型",
        value: "checkPropName",
      },
      {
        type: "text",
        label: "标准范围",
        value: "newUpper",
      },
      {
        type: "text",
        label: "点检值",
        value: "value",
      },
      {
        type: "text",
        label: "点检结果",
        value: "checkResName",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "viewDeatil",
          },
        ],
      },
    ],

    bomTableData: [],
    detailInnerData: {},
    isShowDetailInnerPopup: false,
    detailInnerList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            width: 33.33,
            text: "点检项目编码",
            id: "code",
          },
          {
            width: 33.33,
            text: "点检项名称",
            id: "name",
          },
          {
            width: 33.33,
            text: "点检类型",
            id: "checkPropName",
          },
          {
            width: 33.33,
            text: "标准范围",
            id: "newUpper",
          },
          {
            width: 33.33,
            text: "点检值",
            id: "value",
          },
          {
            width: 33.33,
            text: "点检结果",
            id: "checkResName",
          },
        ],
      },
      {
        type: "image",
        label: "附件信息",
        fileLabel: "图片列表",
        id: "imageList",
        width: 100,
      },
    ],
    bomInnerTotal: 0,
    bomInnerTableColumn: [
      {
        type: "text",
        label: "物料标签",
        value: "barcode",
      },
      {
        type: "text",
        label: "数量",
        value: "num",
      },
      {
        type: "text",
        label: "数量单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "重量",
        value: "weight",
      },
      {
        type: "text",
        label: "重量单位",
        value: "newWeightUnit",
      },
    ],
    bomInnerTableData: [],
    isShowReject: false,
    formRejectObj: {},
    formRejectData: {},
    popupRejectList: [
      {
        label: "驳回理由",
        type: "textarea",
        width: 100,
        value: "",
        id: "checkBillAuditRemark",
      },
    ],
  }),
  computed: {
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  mounted() {
    this.getEnmuData();
  },
  methods: {
    // 获取枚举数据
    async getEnmuData() {
      const { checkBillStateEnum } = await this.$fetchEnumApi(
        "mes-equipment-service",
        ["checkBillStateEnum"]
      );
      const { checkResultEnum } = await this.$fetchEnumApi(
        "mes-equipment-service",
        ["checkResultEnum"]
      );
      const checkResName = this.$findByProperty(
        this.searchHideList,
        "id",
        "checkRes"
      );
      const stateName = this.$findByProperty(
        this.searchHideList,
        "id",
        "state"
      );

      this.$set(stateName, "list", checkBillStateEnum);
      this.$set(checkResName, "list", checkResultEnum);
    },
    async rejectHandle() {
      this.isShowReject = true;
    },
    async operateHandle(val, type) {
      this.currentHandle = type;
      this.$validateData(val, 3);
      const actions = {
        export: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        remove: () => this.removeHandle(this.ids),
        view: () => {
          this.getDetailHandle(val);
          this.getDetailRightHandle(val);
        },
        reject: () => {
          this.formRejectObj = {
            checkBillIdList: val.id ? [val.id] : this.ids,
            checkBillAuditResult: 20,
          };
          this.rejectHandle();
        },
        audit: () => {
          let params = {
            checkBillIdList: val.id ? [val.id] : this.ids,
            checkBillAuditResult: 10,
          };
          this.auditHandle(params, "audit");
        },
      };

      const action = actions[type];
      if (action) action();
    },

    async rejectConfirmHandle() {
      this.$textShow({
        title: this.$t("tip.confirm"),
        content: ["是否确认驳回？"],
      }).then(async () => {
        let { data } = await getAudit(this.formRejectObj);
        if (data.code != 200) return this.$message.error(data.msg);
        this.$message.success(this.$t("msg.success"));
        this.$refs.trTable.clearSelect();
        this.getListHandle();
        this.isShowReject = false;
      });
    },

    removeHandle(ids) {
      this.$textShow({
        title: this.$t("取消确认"),
        content: ["取消后，该单据将无法点检，是否确定取消"],
      })
        .then(async () => {
          let { data } = await remove(ids);
          if (data.code != 200) return;
          this.$message.success(this.$t("msg.success"));
          this.$refs.trTable.clearSelect();
          this.getListHandle();
        })
        .catch(() => {});
    },
    auditHandle(params, textName) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t(`tip.${textName}`)],
      })
        .then(async () => {
          let res = await getAudit(params);
          if (res.data.code != 200) return this.$message.error(res.data.msg);
          this.$message.success(this.$t("msg.success"));
          this.$refs.trTable.clearSelect();
          this.getListHandle();
        })
        .catch(() => {});
    },

    async getDetailHandle(val) {
      const { data } = await getDetail(val.id);
      if (data.code !== 200) return;

      this.detailData = val;

      const col = this.$findByProperty(
        this.detailList,
        "id",
        "stateName",
        "list"
      );
      const checkRes = this.$findByProperty(
        this.detailList,
        "id",
        "checkResName",
        "list"
      );
      checkRes.valueColor = getColor("QT", this.detailData.checkRes);
      col.valueColor = getColor("SQ", val.state);

      data.data.checkBillDetailRespList.forEach((item) => {
        item["checkResNameColor"] = getColor("QT", item.checkRes);
        item["newUpper"] = `${item.upperValue} - ${item.lowerValue}`;
        if (item.checkProp == 20) {
          item.value = "-";
        }
      });
      this.$validateData(data.data);
      this.bomTableData = data.data.checkBillDetailRespList;
      this.isShowDetailPopup = true;
    },
    async getDetailRightHandle(val) {
      let record = await getDetailRight(val.id);

      if (record.data.code !== 200) return;
      // this.$validateData(record.data.data);
      const recordCol = this.$findByProperty(this.recordList, "id", "record");

      recordCol.list = record.data.data.map((item) => {
        return {
          reTime: item.auditTime,
          option: item.checkAuditName,
          iconClass: item.checkAudit == 2 ? "blue-warn" : undefined,
          labelList: [
            {
              label: "审核人员",
              value: item.auditUserName,
            },
          ],
          remarkList: item.remark
            ? [
                {
                  label: "驳回理由",
                  value: item.remark,
                },
              ]
            : [],
        };
      });
    },
    async getDetailTableHandle(val) {
      const { data } = await getDetailInner(val.id);
      if (data.code !== 200) return;
      this.$validateData(data.data);
      const { data: fileRes } = await getFileList(data.data.fileIdList);
      this.detailInnerData = val;
      const checkRes = this.$findByProperty(
        this.detailInnerList,
        "id",
        "checkResName",
        "list"
      );
      checkRes.valueColor = getColor("QT", this.detailInnerData.checkRes);
      this.detailInnerData.imageList = fileRes.data.map((item) => item.link);
      this.isShowDetailInnerPopup = true;
    },

    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
    closeRejectPopup() {
      this.isShowReject = false;
    },
    closeDetailInnerPopup() {
      this.isShowDetailInnerPopup = false;
    },
    searchHandle() {
      this.getListHandle();
    },
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      if (data.code != 200) return;
      console.log(data);

      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.totalNum = Number(data.data.total);
      this.tableData.forEach((item) => {
        item["stateNameColor"] = getColor("SQ", item.state);
        item["checkResNameColor"] = getColor("QT", item.checkRes);
        item["isShowreject"] = item.state != 30;
        item["isShowaudit"] = item.state != 30;
        item["isShowHideBtnList"] = item.state != 30;
      });
    },
  },
};
</script>
